package com.github.config;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONUtil;
import com.github.bean.User;
import com.github.constant.MyConstant;
import com.github.service.UserServer;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Configuration
@RequiredArgsConstructor
@Slf4j
public class UserCacheConfig {
    private final StringRedisTemplate stringRedisTemplate;
    private final UserServer userServer;

    @PostConstruct
    public void initUserCache() {
        if (Boolean.FALSE.equals(stringRedisTemplate.hasKey(MyConstant.Encrypt_Switch))) {
            stringRedisTemplate.opsForValue().set(MyConstant.Encrypt_Switch, "1");
        }
        stringRedisTemplate.delete(MyConstant.UserLoginToken);
        stringRedisTemplate.delete(MyConstant.UserLoginAccount);
        log.info("删除登录缓存信息");
        List<User> allUser = userServer.getAllUser();
        if (CollUtil.isEmpty(allUser)) {
            log.info("用户为空，跳过初始化");
            stringRedisTemplate.delete(MyConstant.UserInfoCache);
            return;
        }

        Map<String, String> userCacheMap = allUser.stream()
                .collect(Collectors.toMap(
                        user -> String.valueOf(user.getAccount()),  // 哈希键：用户ID
                        JSONUtil::toJsonPrettyStr   // 哈希值：用户信息JSON
                ));

        stringRedisTemplate.delete(MyConstant.UserInfoCache);
        stringRedisTemplate.opsForHash().putAll(MyConstant.UserInfoCache, userCacheMap);
        log.info("用户缓存初始化完成");
    }

}
